# mp3_splitter.py
## uv run mp3_splitter.py --src ./talk.mp3 --des ./ --second 600

import os
import argparse
from pydub import AudioSegment

def split_mp3(src_file, dest_folder, seconds):
    # 读取音频文件
    audio = AudioSegment.from_mp3(src_file)

    # 计算每个片段的毫秒数
    segment_length_ms = seconds * 1000

    # 获取文件名（不含扩展名）
    base_name = os.path.splitext(os.path.basename(src_file))[0]

    # 创建输出目录
    os.makedirs(dest_folder, exist_ok=True)

    # 切割并保存
    total_length_ms = len(audio)
    for i in range(0, total_length_ms, segment_length_ms):
        # 截取片段
        segment = audio[i:i + segment_length_ms]
        
        # 构造输出文件名：xxx_001.mp3, xxx_002.mp3...
        segment_filename = f"{base_name}_{str(i // segment_length_ms + 1).zfill(3)}.mp3"
        segment_filepath = os.path.join(dest_folder, segment_filename)

        # 导出为 MP3
        segment.export(segment_filepath, format="mp3")
        print(f"Saved: {segment_filepath}")

    print(f"✅ Splitting completed! Output saved to '{dest_folder}'")

def main():
    parser = argparse.ArgumentParser(description="Split an MP3 file into equal parts by seconds.")
    parser.add_argument("--src", required=True, help="Source MP3 file path")
    parser.add_argument("--des", required=True, help="Destination folder path")
    parser.add_argument("--second", type=int, required=True, help="Length of each segment in seconds")

    args = parser.parse_args()

    if not os.path.isfile(args.src):
        print(f"❌ Error: Source file '{args.src}' does not exist.")
        return

    if args.second <= 0:
        print("❌ Error: --second must be a positive integer.")
        return

    split_mp3(args.src, args.des, args.second)

if __name__ == "__main__":
    main()